﻿using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.WindowsServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using DBContext;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Collections.Generic;
using ViewModel;
using MailKit.Net.Imap;
using MailKit.Net.Smtp;
using MailKit.Security;
using MailKit.Search;
using MailKit;
using MimeKit;

namespace EmailService
{
    

    static class Program
    {
        #region 定时任务Main方法

        static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || ((IList)args).Contains("--console"));

            var webHost = new HostBuilder();

            webHost.ConfigureServices(c => c.AddSingleton<IHostedService, BackgroundWorker>());

            if (isService)
            {
                await webHost.RunAsServiceAsync();
            }
            else
            {
                await webHost.RunConsoleAsync();
            }
        }

        #endregion
    }

    public class BackgroundWorker : IHostedService
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private bool _stopping;
        private Task _backgroundTask;

        public Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("开始定时发送");
            logger.Trace("==============================开始定时发送邮件==============================");

            _backgroundTask = BackgroundTask();
            return Task.CompletedTask;
        }

        private async Task BackgroundTask()
        {
            while (!_stopping)
            {
                //发送前等待2秒钟
                await Task.Delay(TimeSpan.FromSeconds(2));

                #region 业务处理（查询数据库/发送邮件）

                var connstr = "Server=192.168.99.7;Database=test;User ID=gxbid;Password=123456;Charset=utf8";
                var _contextOptions = new DbContextOptionsBuilder()
                .UseMySQL(connstr)
                .Options;
                using (var db = new EmContext(_contextOptions))
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        #region 查询数据

                        var _return = new Gx();

                        //查询配置表的列表
                        var _emConfig = (from v in db.EmailServiceConfigs
                                         where v.IsValid == 1
                                         select v).ToList();

                        //循环配置表查询数据
                        foreach (var em in _emConfig)
                        {
                            //查询关键字分割
                            string[] kw = em.WebKeyword.Split(new char[] { ',', '，', ' ' });

                            //查询爬虫总表
                            var _q = (from _d in db.EmGxykdxs
                                      where _d.Website.Contains(em.WebSite) && (_d.CreateDate > em.LastSuccessTime && _d.CreateDate < DateTime.Now)
                                      orderby _d.Time descending
                                      select new ViewModel.GXBIDModel
                                      {
                                          GId = _d.Id,
                                          Title = _d.Title,
                                          Url = _d.Url,
                                          Time = _d.Time,

                                          Website = _d.Website,
                                          WebUrl = _d.WebUrl,
                                          WebTitle = _d.WebTitle,
                                          WebNode = _d.WebNode,
                                      });

                            //关键字查询（Or方式）
                            _q = _q.Where(x => kw.Any(s => x.Title.Contains(s)));

                            //查询的数据丢给返回的List
                            _return.GXBIDModelList.AddRange(_q.ToList());
                        }

                        #endregion

                        #region 发送邮件
                        var message = new MimeMessage();
                        message.From.Add(new MailboxAddress("小牛", "qinqiuli@gxbidding.cn"));
                        message.To.Add(new MailboxAddress("小牛", "qinqiuli@gxbidding.cn"));
                        //message.To.Add(new MailboxAddress("志兰", "liaozhilan@gxbidding.cn"));
                        message.Subject = "监测网站信息公告";

                        var _body = string.Empty;
                        foreach (var _r in _return.GXBIDModelList)
                        {
                            _body += @"<a href=" + _r.Url + @">"+_r.Time_str+"--"+_r.Website+"--"+_r.Title+@"<a>";
                        }

                        message.Body = new MimeKit.TextPart("html")
                        {
                            Text = _body

                        };

                        using (var client = new SmtpClient())
                        {
                            // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                            client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                            client.Connect("smtp.exmail.qq.com", 465, true);

                            client.Authenticate("qinqiuli@gxbidding.cn", "Qql199476");

                            if (client.IsAuthenticated)
                            {
                                client.Send(message);
                            }
                            else
                            {

                            }
                            client.Disconnect(true);
                        }


                        #endregion
                    }
                    catch (Exception ex)
                    {
                        logger.Trace("EmailService查询数据有误，错误信息为：" + ex);
                    }

                }

                #endregion

                //发送完毕，等待2小时
                await Task.Delay(TimeSpan.FromHours(2));
            }

            logger.Trace("==============================停止定时发送邮件==============================");
            Console.WriteLine("Console.WriteLine：停止定时发送邮件");
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            logger.Trace("==============================停止定时发送邮件==============================");
            Console.WriteLine("Console.WriteLine：停止定时发送邮件");
            _stopping = true;
            if (_backgroundTask != null)
            {
                await _backgroundTask;
            }
        }
    }

    //返回的总表列表定义
    public class Gx
    {
        public List<GXBIDModel> GXBIDModelList { get; set; }

        public Gx()
        {
            GXBIDModelList = new List<GXBIDModel>();
        }
    }
}
